package com.tbit.uqbike.client.remote.sms;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;

import java.net.URLEncoder;


/**
 * 阿里三要素实名认证
 *
 * @author Leon
 * 2020年4月16日 下午2:43:41
 */
@Slf4j
public class PhoneAuthHttpClient {
    private static HttpClient client = null;

    /**
     * 维持单session
     */
    public static HttpClient getClient() {
        if (client == null) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            client = new HttpClient(connectionManager);
            /**设置编码*/
            client.getParams().setContentCharset("UTF-8");
            /**请求超时*/
            client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
            /**读取超时*/
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        }
        return client;
    }

    /**
     * 实名认证
     *
     * @param appcode
     * @param idCard
     * @param realName
     * @return
     */
    public static Boolean authName(String appcode, String idCard, String realName) {
        HttpClient client = getClient();
        GetMethod get = null;
        try {
            String url = "http://zidv2.market.alicloudapi.com/idcard/VerifyIdcardv2?cardNo=" + idCard + "&realName=" + URLEncoder.encode(realName, "UTF-8");
            get = new GetMethod(url);
            get.setRequestHeader("Authorization", "APPCODE " + appcode);
            client.executeMethod(get);
            String result = get.getResponseBodyAsString();
            Integer httpCode = get.getStatusCode();
            if (httpCode != 200) {
                log.error("" + get.getResponseHeader("X-Ca-Error-Code"));
            }
            log.info("回复=" + result);
            int code = JSON.parseObject(result).getIntValue("error_code");
            if (code == 0) {
                Boolean isok = JSON.parseObject(result).getJSONObject("result").getBooleanValue("isok");
                if (isok) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            get.releaseConnection();
        }

        return false;
    }

    public static void main(String[] args) {
        System.out.println(authName("43a82a2eebce4247b0f816e8a7b1fa0b", "440981198805083516", "梁飞龙"));
    }
}